package com.search.xht.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.ljw.store.entity.Store;
import com.marchant.lyh.domain.Item;

@Transactional
public class SearchDaoImp implements SearchDao{
	@Resource
	private SessionFactory sessionFactory;
	private Query query;
	
	public List<Item> searchItem(String key, int pageNumber, int pageSize) {
		// TODO Auto-generated method stub
		query=sessionFactory.getCurrentSession().createQuery("from Item where itemName like ? order by itemId desc");
		List<Item> itemList = new ArrayList<Item>();
		key="%"+key+"%";
		query.setString(0, key);
		query.setFirstResult((pageNumber - 1)*pageSize);
		query.setMaxResults(pageSize);
		itemList = query.list();
		return itemList;
	}
	
	public List<Store> searchShop(String key, int pageNumber, int pageSize) {
		// TODO Auto-generated method stub
		query=sessionFactory.getCurrentSession().createQuery("from Store where shopName like ? order by shopId desc");
		List<Store> shopList = new ArrayList<Store>();
		key="%"+key+"%";
		query.setString(0, key);
		query.setFirstResult((pageNumber - 1)*pageSize);
		query.setMaxResults(pageSize);
		shopList = query.list();
		return shopList;
	}
	
	
	public int itemAmount(String key) {
		int itemAmount = 0;
		query=sessionFactory.getCurrentSession().createQuery("select count(*) from Item where itemName like ?");	
		key="%"+key+"%";
		query.setString(0, key);
		long  l = (Long)query.uniqueResult();
		itemAmount = (int)l;
		return itemAmount;
	}
	
	public int storeAmount(String key) {
		int storeAmount = 0;
		query=sessionFactory.getCurrentSession().createQuery("select count(*) from Store where shopName like ?");
		key="%"+key+"%";
		query.setString(0, key);
		long  l = (Long)query.uniqueResult();
		storeAmount = (int)l;
		return storeAmount;
	}
	
	public int[] pageNumber(int amount, String pageNumberStr, int pageSize) {
		// TODO Auto-generated method stub
		int[] paging = new int[2];
		int pageNumber = 1;
		pageNumber = Integer.parseInt(pageNumberStr);
		if(pageNumber <= 0){
			pageNumber = 1;
		}
		int totalPage = 1;
		if(amount > 0){
			totalPage = amount%pageSize==0?(amount/pageSize):(amount/pageSize+1);
		}
		if(pageNumber > totalPage){
			pageNumber = totalPage;
		}
		paging[0] = pageNumber;
		paging[1] = totalPage;
		return paging;
	}

	public List<Item> getAllItem() {
		// TODO Auto-generated method stub
		Query query=sessionFactory.getCurrentSession().createQuery("from Item");	
		List<Item> item= query.list();
		return item;
	}
	
}
